package de.preamp.clients.java.lib;

import java.io.IOException;
import java.util.SortedSet;

import javax.swing.event.ChangeEvent;

import org.json.JSONException;

import de.preamp.clients.java.data.Album;
import de.preamp.clients.java.data.Artist;
import de.preamp.clients.java.data.Track;

/**
 * A class managing the content for a single artist from media-library using the
 * preamp server and local cache. It can be used as a kind of proxy object to
 * the database.
 * 
 * @author André Stannek
 * @since 2010-03-22
 * @version 2010-03-23
 */
public class ArtistLibrary extends AbstractLibrary
{
    /**
     * Generated UID.
     */
    private static final long serialVersionUID = 5023644138998013806L;

    /**
     * .
     */
    private final transient Artist artist;

    /**
     * creates a new artist-library and fills it with all albums and tracks
     * available on the server.
     * 
     * @param artist
     *            the artist for this library
     * @throws JSONException
     *             if library couldn't be created because the server returned
     *             broken results.
     * @throws IOException
     *             if library couldn't be created because the server connection
     *             was impossible.
     */
    public ArtistLibrary(final Artist artist) throws JSONException, IOException
    {
	this.artist = artist;
	update();
    }

    @Override
    public final void update() throws JSONException, IOException
    {
	addElement(artist);
	final SortedSet<Album> albums = artist.getAlbums();
	for (final Album album : albums)
	{
	    album.addChangeListener(this);
	    addElement(album);

	    for (final Track track : album.getTracks())
	    {
		track.addChangeListener(this);
		addElement(track);
	    }
	}
	fireContentsChanged(this, 0, this.getSize() - 1);
    }

    @Override
    public final void stateChanged(final ChangeEvent event)
    {
	final int index = this.indexOf(event.getSource());
	fireContentsChanged(this, index, index + 1);
    }
}
